"""
企业微信服务类
处理企业微信消息的发送和接收
"""
import requests
import time
from typing import Dict, Any, Optional
from config import (
    WECHAT_CORP_ID, WECHAT_CORP_SECRET, WECHAT_AGENT_ID,
    WECHAT_ACCESS_TOKEN_URL, WECHAT_SEND_MESSAGE_URL,
    WECHAT_MAX_MESSAGE_LENGTH, WECHAT_MAX_MARKDOWN_LENGTH,
    BOT_NAME, logger, error_logger, PROMETHEUS_URL
)


class WeChatService:
    """企业微信服务类"""
    
    def __init__(self):
        self.corp_id = WECHAT_CORP_ID
        self.corp_secret = WECHAT_CORP_SECRET
        self.agent_id = WECHAT_AGENT_ID
        self.access_token = None
        self.token_expires_at = 0
        
        # Prometheus连接缓存
        self.prometheus_client = None
        self.prometheus_created_at = 0
        self.prometheus_cache_duration = 60  # 1分钟缓存时间
        
    def get_access_token(self) -> Optional[str]:
        """获取企业微信访问令牌"""
        try:
            # 如果token还有效，直接返回
            if self.access_token and time.time() < self.token_expires_at:
                logger.debug(f"使用缓存的访问令牌，剩余时间: {self.token_expires_at - time.time():.0f}秒")
                return self.access_token
                
            logger.info("开始获取企业微信访问令牌")
            
            # 获取新的token
            params = {
                'corpid': self.corp_id,
                'corpsecret': self.corp_secret
            }
            
            logger.debug(f"请求参数: corp_id={self.corp_id}, corp_secret={'*' * len(self.corp_secret) if self.corp_secret else 'None'}")
            
            response = requests.get(WECHAT_ACCESS_TOKEN_URL, params=params, timeout=10)
            response.raise_for_status()
            
            data = response.json()
            logger.debug(f"企业微信API响应: {data}")
            
            if data.get('errcode') == 0:
                self.access_token = data['access_token']
                # 提前5分钟过期，避免边界情况
                self.token_expires_at = time.time() + data['expires_in'] - 300
                logger.info(f"企业微信访问令牌获取成功，有效期: {data['expires_in']}秒")
                return self.access_token
            else:
                error_msg = f"获取企业微信访问令牌失败: {data}"
                logger.error(error_msg)
                error_logger.error(f"企业微信访问令牌获取失败: {data}")
                return None
                
        except Exception as e:
            error_msg = f"获取企业微信访问令牌异常: {e}"
            logger.error(error_msg)
            error_logger.error(f"企业微信访问令牌获取异常: {e}", exc_info=True)
            return None
    
    def get_prometheus_client(self):
        """获取Prometheus客户端连接（带缓存机制）"""
        try:
            current_time = time.time()
            
            # 检查是否需要创建新连接
            if (self.prometheus_client is None or 
                current_time - self.prometheus_created_at > self.prometheus_cache_duration):
                
                logger.info("创建新的Prometheus连接")
                from prometheus_api_client import PrometheusConnect
                self.prometheus_client = PrometheusConnect(url=PROMETHEUS_URL)
                self.prometheus_created_at = current_time
                logger.debug(f"Prometheus连接已创建，缓存时间: {self.prometheus_cache_duration}秒")
            else:
                remaining_time = self.prometheus_cache_duration - (current_time - self.prometheus_created_at)
                logger.debug(f"复用现有Prometheus连接，剩余缓存时间: {remaining_time:.1f}秒")
            
            return self.prometheus_client
            
        except Exception as e:
            logger.error(f"获取Prometheus客户端异常: {e}")
            error_logger.error(f"Prometheus客户端获取失败: {e}", exc_info=True)
            return None
    
    def cleanup_prometheus_connection(self):
        """清理过期的Prometheus连接"""
        try:
            if self.prometheus_client is not None:
                current_time = time.time()
                if current_time - self.prometheus_created_at > self.prometheus_cache_duration:
                    logger.info("清理过期的Prometheus连接")
                    self.prometheus_client = None
                    self.prometheus_created_at = 0
        except Exception as e:
            logger.error(f"清理Prometheus连接异常: {e}")
    
    def get_connection_status(self):
        """获取连接状态信息"""
        if self.prometheus_client is None:
            return "无连接"
        
        current_time = time.time()
        remaining_time = self.prometheus_cache_duration - (current_time - self.prometheus_created_at)
        return f"连接有效，剩余时间: {remaining_time:.1f}秒"
    
    def split_message(self, content: str, max_length: int) -> list:
        """分割长消息为多个短消息"""
        if len(content) <= max_length:
            return [content]
        
        messages = []
        lines = content.split('\n')
        current_message = ""
        
        for line in lines:
            # 如果单行就超过限制，需要截断
            if len(line) > max_length:
                # 先保存当前消息
                if current_message:
                    messages.append(current_message.strip())
                    current_message = ""
                
                # 截断长行
                while len(line) > max_length:
                    messages.append(line[:max_length])
                    line = line[max_length:]
                
                # 如果还有剩余内容，继续处理
                if line:
                    current_message = line + '\n'
            else:
                # 检查添加这行后是否超限
                test_message = current_message + line + '\n'
                if len(test_message) > max_length:
                    # 超限，保存当前消息
                    if current_message:
                        messages.append(current_message.strip())
                    current_message = line + '\n'
                else:
                    current_message = test_message
        
        # 添加最后一个消息
        if current_message:
            messages.append(current_message.strip())
        
        return messages
    
    def send_text_message(self, content: str, to_user: str = "@all") -> bool:
        """发送文本消息（支持长消息分割）"""
        try:
            logger.info(f"开始发送企业微信文本消息 - 接收者: {to_user}, 内容长度: {len(content)}")
            
            # 分割长消息
            messages = self.split_message(content, WECHAT_MAX_MESSAGE_LENGTH)
            
            if len(messages) > 1:
                logger.info(f"消息过长，分割为 {len(messages)} 条消息发送")
            
            access_token = self.get_access_token()
            if not access_token:
                logger.error("无法获取企业微信访问令牌，消息发送失败")
                return False
                
            url = f"{WECHAT_SEND_MESSAGE_URL}?access_token={access_token}"
            
            success_count = 0
            for i, message in enumerate(messages):
                try:
                    # 添加分页标识
                    if len(messages) > 1:
                        page_info = f"\n\n--- 第 {i+1}/{len(messages)} 页 ---"
                        if i == 0:
                            message += page_info
                        else:
                            message = f"--- 第 {i+1}/{len(messages)} 页 ---\n\n" + message
                    
                    data = {
                        "touser": to_user,
                        "msgtype": "text",
                        "agentid": self.agent_id,
                        "text": {
                            "content": message
                        }
                    }
                    
                    logger.debug(f"发送消息 {i+1}/{len(messages)} - 长度: {len(message)}")
                    
                    response = requests.post(url, json=data, timeout=10)
                    response.raise_for_status()
                    
                    result = response.json()
                    
                    if result.get('errcode') == 0:
                        success_count += 1
                        logger.info(f"消息 {i+1}/{len(messages)} 发送成功 - 消息ID: {result.get('msgid', 'N/A')}")
                    else:
                        logger.error(f"消息 {i+1}/{len(messages)} 发送失败: {result}")
                        error_logger.error(f"企业微信消息发送失败 - 接收者: {to_user}, 消息 {i+1}, 错误: {result}")
                    
                    # 避免发送过快，稍作延迟
                    if i < len(messages) - 1:
                        time.sleep(0.5)
                        
                except Exception as e:
                    logger.error(f"发送消息 {i+1}/{len(messages)} 异常: {e}")
                    error_logger.error(f"企业微信消息发送异常 - 接收者: {to_user}, 消息 {i+1}, 错误: {e}", exc_info=True)
            
            if success_count == len(messages):
                logger.info(f"所有消息发送成功 - 共 {success_count} 条")
                return True
            elif success_count > 0:
                logger.warning(f"部分消息发送成功 - 成功 {success_count}/{len(messages)} 条")
                return True
            else:
                logger.error("所有消息发送失败")
                return False
                
        except Exception as e:
            error_msg = f"发送企业微信消息异常: {e}"
            logger.error(error_msg)
            error_logger.error(f"企业微信消息发送异常 - 接收者: {to_user}, 错误: {e}", exc_info=True)
            
    
    
    def send_markdown_message(self, content: str, to_user: str = "@all") -> bool:
        """发送Markdown消息（支持长消息分割）"""
        try:
            logger.info(f"开始发送企业微信Markdown消息 - 接收者: {to_user}, 内容长度: {len(content)}")
            
            # 分割长消息
            messages = self.split_message(content, WECHAT_MAX_MARKDOWN_LENGTH)
            
            if len(messages) > 1:
                logger.info(f"Markdown消息过长，分割为 {len(messages)} 条消息发送")
            
            access_token = self.get_access_token()
            if not access_token:
                logger.error("无法获取企业微信访问令牌，消息发送失败")
                return False
                
            url = f"{WECHAT_SEND_MESSAGE_URL}?access_token={access_token}"
            
            success_count = 0
            for i, message in enumerate(messages):
                try:
                    # 添加分页标识
                    if len(messages) > 1:
                        page_info = f"\n\n--- 第 {i+1}/{len(messages)} 页 ---"
                        if i == 0:
                            message += page_info
                        else:
                            message = f"--- 第 {i+1}/{len(messages)} 页 ---\n\n" + message
                    
                    data = {
                        "touser": to_user,
                        "msgtype": "markdown",
                        "agentid": self.agent_id,
                        "markdown": {
                            "content": message
                        }
                    }
                    
                    logger.debug(f"发送Markdown消息 {i+1}/{len(messages)} - 长度: {len(message)}")
                    
                    response = requests.post(url, json=data, timeout=10)
                    response.raise_for_status()
                    
                    result = response.json()
                    
                    if result.get('errcode') == 0:
                        success_count += 1
                        logger.info(f"Markdown消息 {i+1}/{len(messages)} 发送成功 - 消息ID: {result.get('msgid', 'N/A')}")
                    else:
                        logger.error(f"Markdown消息 {i+1}/{len(messages)} 发送失败: {result}")
                        error_logger.error(f"企业微信Markdown消息发送失败 - 接收者: {to_user}, 消息 {i+1}, 错误: {result}")
                    
                    # 避免发送过快，稍作延迟
                    if i < len(messages) - 1:
                        time.sleep(0.5)
                        
                except Exception as e:
                    logger.error(f"发送Markdown消息 {i+1}/{len(messages)} 异常: {e}")
                    error_logger.error(f"企业微信Markdown消息发送异常 - 接收者: {to_user}, 消息 {i+1}, 错误: {e}", exc_info=True)
            
            if success_count == len(messages):
                logger.info(f"所有Markdown消息发送成功 - 共 {success_count} 条")
                return True
            elif success_count > 0:
                logger.warning(f"部分Markdown消息发送成功 - 成功 {success_count}/{len(messages)} 条")
                return True
            else:
                logger.error("所有Markdown消息发送失败")
                return False
                
        except Exception as e:
            logger.error(f"发送企业微信Markdown消息异常: {e}")
            return False
    
    
    
    def format_prometheus_data(self, data: str, project_name: str = None, query_type: str = None) -> str:
        """格式化Prometheus数据为Markdown格式（精简版）"""
        try:
            lines = data.strip().split('\n')
            if not lines or lines[0] == '':
                return "暂无数据"
            
            # 精简的Markdown格式
            markdown_content = f"📊 **{project_name or '监控数据'}** - {query_type or '查询结果'}\n\n"
            
            # 优化数据格式，减少冗余信息
            data_lines = []
            for line in lines:
                if line.strip():
                    # 简化字段名
                    simplified_line = line
                    simplified_line = simplified_line.replace('检测指标:', '指标:')
                    simplified_line = simplified_line.replace('检测实例:', '实例:')
                    simplified_line = simplified_line.replace('检测POD:', 'POD:')
                    simplified_line = simplified_line.replace('检测POD状态:', '状态:')
                    simplified_line = simplified_line.replace('检测节点:', '节点:')
                    simplified_line = simplified_line.replace('检测值:', '值:')
                    data_lines.append(simplified_line)
            
            # 使用更简洁的代码块格式
            markdown_content += "```\n"
            markdown_content += '\n'.join(data_lines)
            markdown_content += "\n```"
            
            return markdown_content
            
        except Exception as e:
            logger.error(f"格式化Prometheus数据异常: {e}")
            return f"数据格式化失败: {str(e)}"
    
    def send_prometheus_alert(self, alert_data: Dict[str, Any]) -> bool:
        """发送Prometheus告警消息"""
        try:
            # 构建告警消息
            alert_msg = f"🚨 **Prometheus告警**\n\n"
            alert_msg += f"**告警名称**: {alert_data.get('alertname', 'Unknown')}\n"
            alert_msg += f"**状态**: {alert_data.get('status', 'Unknown')}\n"
            alert_msg += f"**严重程度**: {alert_data.get('severity', 'Unknown')}\n"
            alert_msg += f"**实例**: {alert_data.get('instance', 'Unknown')}\n"
            alert_msg += f"**描述**: {alert_data.get('description', 'No description')}\n"
            alert_msg += f"**时间**: {alert_data.get('startsAt', 'Unknown')}\n"
            
            return self.send_markdown_message(alert_msg)
            
        except Exception as e:
            logger.error(f"发送Prometheus告警消息异常: {e}")
            return False


# 创建全局实例
wechat_service = WeChatService()
